package com.thb.pay.channel.alipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.thb.pay.api.order.vo.req.PayOrderReq;
import com.thb.pay.channel.AbsPaymentService;
import com.thb.pay.comm.utils.ChannelConstants;
import com.thb.pay.comm.utils.PaymentResult;
import com.thb.pay.core.utils.MoneyUtils;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.stereotype.Component;

/**
 * @类名称 AliPaymentService
 * @类描述 <pre>支付宝平台支付接口</pre>
 * @作者 lucky
 * @创建时间 2019/10/25
 * @版本 v1.01
 */
@Component
public class AliPaymentService extends AbsPaymentService {

    @Override
    public String channel() {
        return ChannelConstants.CHANNEL_ALI;
    }


    /**
     * @param payOrder 支付订单请求参数
     * @Description 支付宝扫码支付
     * <p>收银员通过收银台或商户后台调用支付宝接口，生成二维码后，展示给用户，由用户扫描二维码完成订单支付。</p>
     * @Author lucky
     * @data 2019/11/11 22:45
     */
    public PaymentResult aliPayQr(PayOrderReq payOrder) {
        //1.解析获取支付宝对应请求配置参数
        AliPaymentConfig aliPaymentConfig = new AliPaymentConfig(this.getThirdPayConfig(payOrder));
        // 1.封装请求支付信息
        AlipayTradePrecreateModel alipayTradePrecreateModel = new AlipayTradePrecreateModel();
        alipayTradePrecreateModel.setOutTradeNo(payOrder.getOrderNum());
        alipayTradePrecreateModel.setSubject(payOrder.getSubject());
        alipayTradePrecreateModel.setTotalAmount(MoneyUtils.convertCent2Dollar(payOrder.getAmount().toString()));
        alipayTradePrecreateModel.setBody(payOrder.getBody());
        // 获取objParams参数
        String orderExtra = payOrder.getExtra();
        if (StrUtil.isNotEmpty(orderExtra)) {
            try {
                JSONObject objParamsJson = JSON.parseObject(orderExtra);
                if (StrUtil.isNotEmpty(objParamsJson.getString("discountable_amount"))) {
                    //可打折金额
                    alipayTradePrecreateModel.setDiscountableAmount(objParamsJson.getString("discountable_amount"));
                }
                if (StrUtil.isNotEmpty(objParamsJson.getString("undiscountable_amount"))) {
                    //不可打折金额
                    alipayTradePrecreateModel.setUndiscountableAmount(objParamsJson.getString("undiscountable_amount"));
                }
            } catch (Exception e) {
                logger.error("ali.payMethod.aliPayQr.parse.extra.error.", orderExtra);
            }
        }
        AlipayTradePrecreateRequest alipayTradePrecreateRequest = new AlipayTradePrecreateRequest();
        alipayTradePrecreateRequest.setBizModel(alipayTradePrecreateModel);
//        alipayTradePrecreateRequest.setNotifyUrl(payConfig.getNotifyUrl(getChannelName()));
//        alipayTradePrecreateRequest.setReturnUrl(payConfig.getReturnUrl(getChannelName()));
//        String aliResult;
//        String codeUrl = "";
//        JSONObject retObj = buildRetObj();
//        AlipayClient alipayClient = aliPaymentConfig.buildAlipayClient();
//        try {
//            aliResult = client.execute(alipay_request).getBody();
//            JSONObject aliObj = JSONObject.parseObject(aliResult);
//            JSONObject aliResObj = aliObj.getJSONObject("alipay_trade_precreate_response");
//            codeUrl = aliResObj.getString("qr_code");
//        } catch (AlipayApiException e) {
//            _log.error(e, "");
//            retObj.put("errDes", "下单失败[" + e.getErrMsg() + "]");
//            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
//            return retObj;
//        } catch (Exception e) {
//            _log.error(e, "");
//            retObj.put("errDes", "下单失败[调取通道异常]");
//            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
//            return retObj;
//        }
//        _log.info("{}生成支付宝二维码：codeUrl={}", logPrefix, codeUrl);
//        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrderId, null);
//
//        String codeImgUrl = payConfig.getPayUrl() + "/qrcode_img_get?url=" + codeUrl + "&widht=200&height=200";
//        StringBuffer payForm = new StringBuffer();
//        String toPayUrl = payConfig.getPayUrl() + "/alipay/pay_" + type + ".htm";
////        payForm.append("<form style=\"display: none\" action=\""+toPayUrl+"\" method=\"post\">");
////        payForm.append("<input name=\"mchOrderNo\" value=\""+payOrder.getMchOrderNo()+"\" >");
////        payForm.append("<input name=\"payOrderId\" value=\""+payOrder.getPayOrderId()+"\" >");
////        payForm.append("<input name=\"amount\" value=\""+payOrder.getAmount()+"\" >");
////        payForm.append("<input name=\"codeUrl\" value=\""+codeUrl+"\" >");
////        payForm.append("<input name=\"codeImgUrl\" value=\""+codeImgUrl+"\" >");
////        payForm.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >");
////        payForm.append("</form>");
////        payForm.append("<script>document.forms[0].submit();</script>");
//
//        toPayUrl += "?mchOrderNo=" + payOrder.getMchOrderNo();
//        toPayUrl += "&payOrderId=" + payOrder.getPayOrderId();
//        toPayUrl += "&amount=" + payOrder.getAmount();
//        toPayUrl += "&codeUrl=" + codeUrl;
//        toPayUrl += "&codeImgUrl=" + codeImgUrl;
//
//        payForm.append("<div id=\"Content\">\n" +
//                "    <div class=\"tabPages\">我们正在为您连接银行，请稍等......</div>\n" +
//                "</div>");
//        payForm.append("<script> window.location.href =\"" + toPayUrl + "\" </script>");
//
//        retObj.put("payOrderId", payOrderId);
//        JSONObject payInfo = new JSONObject();
//        payInfo.put("payUrl", payForm);
//        payInfo.put("payJumpUrl", toPayUrl);
//        payInfo.put("payMethod", PayConstant.PAY_METHOD_FORM_JUMP);
//        retObj.put("payParams", payInfo);
//        _log.info("###### 商户统一下单处理完成 ######");
        return PaymentResult.ok();
    }


}
